<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="任务名称" prop="taskName">
        <el-input v-model="formData.taskName" placeholder="请输入任务名称" />
      </el-form-item>

      <el-form-item label="任务参数" prop="taskParams">
        <el-checkbox-group v-model="formData.taskParams">
          <el-checkbox
            v-for="dict in getStrDictOptions(DICT_TYPE.TASK_PARAMS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>


      <el-form-item label="匹配对象" prop="matchType">
        <el-select v-model="formData.matchType" placeholder="请选择">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PHONE_MATCH_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="检索时间" prop="retrievalDays">
        <el-input v-model="formData.retrievalDays" placeholder="请输入检索时间" />
      </el-form-item>

      <el-form-item label="上传文件" prop="excelFile">
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="true"
          :limit="1"
          accept=".xlsx,.xls"
          :on-change="handleFileChange"
        >
          <el-button type="primary">选择 Excel 文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="downloadTemplate">下载模板</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import {getStrDictOptions, DICT_TYPE} from '@/utils/dict'
import { DataMatchTaskApi } from '@/api/vos/datamatchtask'
import download from "@/utils/download";

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formRef = ref()
const uploadRef = ref()

const formData = ref({
  id: undefined,
  taskName: undefined,
  taskParams: [],
  retrievalDays: undefined,
  excelFile: null, // 新增字段
  matchType: undefined,
})

const formRules = reactive({
  taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  retrievalDays: [{ required: true, message: '请输入检索时间', trigger: 'blur' }],
  // 可选：excelFile: [{ required: true, message: '请上传 Excel 文件', trigger: 'change' }],
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      const data = await DataMatchTaskApi.getDataMatchTask(id)
      formData.value = { ...data, excelFile: null } // 注意不带文件
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

/** 文件选择处理 */
const handleFileChange = (file: any) => {
  formData.value.excelFile = file.raw
}

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = new FormData()
    data.append('taskName', formData.value.taskName)
    data.append('matchType', formData.value.matchType)
    data.append('retrievalDays', formData.value.retrievalDays)
    formData.value.taskParams.forEach((param: string) => {
      data.append('taskParams', param)
    })
    if (formData.value.excelFile) {
      data.append('file', formData.value.excelFile)
    }

    if (formType.value === 'create') {
      await DataMatchTaskApi.createDataMatchTask(data)
      message.success(t('common.createSuccess'))
    } else {
      data.append('id', formData.value.id)
      await DataMatchTaskApi.updateDataMatchTask(data)
      message.success(t('common.updateSuccess'))
    }

    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 下载模板 */
const downloadTemplate = async () => {
  const res = await DataMatchTaskApi.importDownloadTemplate()
  download.excel(res, '批量下载导入模版.xls')
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    taskName: undefined,
    taskParams: [],
    retrievalDays: undefined,
    excelFile: null,
    matchType: undefined,
  }
  uploadRef.value?.clearFiles()
  formRef.value?.resetFields()
}
</script>
